<!-- MainLayout.vue -->
<script setup lang="ts">
import { onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import Vue3DraggableResizable from 'vue3-draggable-resizable';
import 'vue3-draggable-resizable/dist/Vue3DraggableResizable.css';
import BrowserTabs from '@/views/Square/PracticeSquare/details/components/BrowserTabs.vue';
import SideManual from '@/views/Square/PracticeSquare/details/components/SideManual.vue';
import TopNavBar from '@/views/Square/PracticeSquare/details/components/TopNavBar.vue';
import { getPracticeSections } from '@/api/practiceSquare/practiceSquare';
import { message } from 'ant-design-vue';
import { useRoute } from 'vue-router';

const route = useRoute();
// 链接点击处理函数
const iframeUrl = ref<{ url: string; timestamp: number } | null>(null);

const handleLinkClick = (url: string) => {
  iframeUrl.value = { url, timestamp: Date.now() };
};

// 添加章节数据相关的状态
const sections = ref<Array<{ id: string; content: string; title: string }>>([]);
const loading = ref(false);

// 添加数据加载函数
const loadSections = async () => {
  loading.value = true;
  try {
    const practiceId = route.query.customPrimary as string || '';
    const fetchedData = await getPracticeSections(practiceId);
    // 对章节数据按页码排序
    fetchedData.sort((a: any, b: any) => a.page - b.page);

    // 转换为 sections 格式
    sections.value = fetchedData.map((item: any) => ({
      id: `section${item.page}`,
      content: item.content,
      title: item.title,
    }));
  }
  catch (error: any) {
    console.error('加载章节数据时出错:', error);
    const errorMsg = error.response?.data?.msg || '无法加载数据，请稍后重试';
    message.error(errorMsg);
  }
  finally {
    loading.value = false;
  }
};
// 定义左侧面板的状态
const leftPanel = reactive({
  x: 0,
  y: 0,
  w: 500,
  h: window.innerHeight - 60, // 减去顶部导航栏高度
  visible: true, // 用于控制SideManual是否可见
});

// 控制是否全屏
const isFullscreen = ref(false);

// 获取窗口尺寸
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;

// 拖动相关
let isDragging = false;
let initialMouseX = 0; // 添加初始鼠标位置
let initialPanelWidth = 0; // 添加初始面板宽度

const onMouseMove = (e: MouseEvent) => {
  if (!isDragging)
    return;
  const deltaX = e.clientX - initialMouseX; // 计算鼠标移动距离
  const newWidth = initialPanelWidth + deltaX; // 基于初始宽度计算新宽度

  if (newWidth >= 500 && newWidth <= windowWidth - 500)
    leftPanel.w = newWidth;
};

const onMouseUp = () => {
  isDragging = false;
  document.removeEventListener('mousemove', onMouseMove);
  document.removeEventListener('mouseup', onMouseUp);
};

const onMouseDown = (e: MouseEvent) => {
  isDragging = true;
  initialMouseX = e.clientX; // 记录初始鼠标位置
  initialPanelWidth = leftPanel.w; // 记录初始面板宽度
  document.addEventListener('mousemove', onMouseMove);
  document.addEventListener('mouseup', onMouseUp);
};

// 添加组件刷新控制
const componentKey = ref(0);

// 添加 resize 处理函数
const handleResize = () => {
  componentKey.value++; // 更新 key 值以强制刷新组件
  // 更新面板尺寸
  leftPanel.h = window.innerHeight - 60;
};
onMounted(() => {
  window.addEventListener('resize', handleResize);
  loadSections();
});
onBeforeUnmount(() => {
  window.addEventListener('resize', handleResize);
  document.removeEventListener('mousemove', onMouseMove);
  document.removeEventListener('mouseup', onMouseUp);
});

// 切换面板显示
const toggleSideManual = () => {
  leftPanel.visible = !leftPanel.visible;
};

// 切换全屏显示状态
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value;
  leftPanel.visible = !isFullscreen.value; // 全屏时隐藏左侧面板，退出全屏时显示
};

const onAdviceBtnClicked = () => {
  window.open(import.meta.env.VITE_ADVICE_URL, '_blank');
}
</script>

<template>
  <div class="main-layout">
    <!-- 顶部导航栏 -->
    <TopNavBar />

    <div class="content-container">
      <!-- 左侧 Tabs -->
      <a-tabs
        tab-position="left"
        class="vertical-tabs"
        @tab-click="toggleSideManual"
      >
        <a-tab-pane key="1">
          <template #tab>
            <div class="vertical-tab-text">
              <span>操</span>
              <span>作</span>
              <span>手</span>
              <span>册</span>
            </div>
          </template>
        </a-tab-pane>
      </a-tabs>

      <!-- 左侧可拖动、可调整大小的面板 -->
      <Vue3DraggableResizable
        v-if="leftPanel.visible && !isFullscreen"
        v-model:x="leftPanel.x"
        v-model:y="leftPanel.y"
        v-model:w="leftPanel.w"
        v-model:h="leftPanel.h"
        :min-w="500"
        :min-h="windowHeight - 60"
        :max-w="windowWidth - 500"
        :max-h="windowHeight - 60"
        drag-handle=".drag-handle"
        :resizable="false"
        :draggable="false"
        class="left-panel"
      >
        <!-- 左侧内容 -->
        <SideManual
          :key="componentKey"
          :is-fullscreen="isFullscreen"
          :sections="sections"
          :loading="loading"
          @link-click="handleLinkClick"
          @close="toggleSideManual"
          @toggle-fullscreen="toggleFullscreen"
        />
        <!-- 拖动条 -->
        <div class="drag-handle" @mousedown="onMouseDown" />
      </Vue3DraggableResizable>

      <!-- 全屏显示时的面板 -->
      <SideManual
        v-if="isFullscreen"
        :key="componentKey"
        :is-fullscreen="isFullscreen"
        :sections="sections"
        :loading="loading"
        @link-click="handleLinkClick"
        @close="toggleFullscreen"
        @toggle-fullscreen="toggleFullscreen"
      />

      <!-- 右侧内容区域 -->
      <div v-if="!isFullscreen" class="right-panel">
        <BrowserTabs :iframe-url="iframeUrl" />
      </div>
      <a-tabs
        tab-position="right"
        class="vertical-tabs"
        @tab-click="onAdviceBtnClicked"
      >
        <a-tab-pane key="1">
          <template #tab>
            <div class="vertical-tab-text1">
              <span>问</span>
              <span>题</span>
              <span>反</span>
              <span>馈</span>
            </div>
          </template>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
</template>

<style scoped>
.main-layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
}

/* 顶部导航栏 */
.top-navbar {
  height: 3.75rem; /* 60px = 3.75rem */
  width: 100%;
}

/* 内容容器 */
.content-container {
  display: flex;
  flex: 1;
  position: relative;
  height: calc(100vh - 3.75rem); /* 减去顶部导航栏的高度 */
}

/* 左侧 Tabs */
.vertical-tabs {
  width: 4rem; /* 64px = 4rem */
  height: 100%;
  background-color: #f0f2f5; /* 添加背景色使得 Tabs 更明显 */
}

/* 标签中的文本垂直排列 */
.vertical-tab-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 1rem; /* 16px = 1rem */
}

.vertical-tab-text1{
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 1rem; /* 16px = 1rem */
}

/* 左侧面板 */
.left-panel {
  position: relative;
  height: 100%;
  padding: 0rem; /* 10px = 0.625rem */
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止溢出 */
}

/* 右侧面板 */
.right-panel {
  flex: 1;
  overflow: auto;
  display: flex;
  flex-direction: column; /* 确保右侧内容区域垂直排列 */
}

/* 拖动条 */
.drag-handle {
  position: absolute;
  top: 0;
  right: -0.3125rem; /* -5px = -0.3125rem */
  width: 0.625rem; /* 10px = 0.625rem */
  height: 100%;
  cursor: col-resize;
  z-index: 10;
}
body {
  overflow: hidden; /* 防止页面滚动 */
}
</style>
